package com.distribution.system.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.distribution.common.core.controller.BaseController;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.common.core.domain.entity.SysUser;
import com.distribution.common.core.page.TableDataInfo;
import com.distribution.common.utils.ip.IpUtils;
import com.distribution.system.domain.bo.Recommended;
import com.distribution.system.domain.dto.TodayOrderLimitDto;
import com.distribution.system.domain.entity.CmccDaProduct;
import com.distribution.system.domain.entity.CmccDaProxyProductManage;
import com.distribution.system.domain.req.*;
import com.distribution.system.mapper.SysUserMapper;
import com.distribution.system.service.CmccDaProductService;
import com.distribution.system.service.CmccDaProxyProductManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 推荐商品级别增删改成操作
 *
 * @since 2023-05-20 20:46:37
 */
@RestController
@RequestMapping(value = "/cmccDaProduct")
@Slf4j
@Validated
public class CmccDaProductController extends BaseController {
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    CmccDaProductService cmccDaProductService;
    @Resource
    CmccDaProxyProductManageService cmccDaProxyProductManageService;

    /**
     * 推荐商品列表查询
     */
    @PreAuthorize("@ss.hasPermi('system:product:list')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody CmccDaProductListReq cmccDaProductListReq) {
        // 如果是直播运营部则设置推广渠道
        SysUser sysUser = sysUserMapper.selectUserById(getUserId());
        if (sysUser.getDeptId() == 102) cmccDaProductListReq.setPromoteChannel("1");
        startPage();
        //确保不是聚合商品
        cmccDaProductListReq.setMergeProductFlag("0");
        List<CmccDaProduct> productListByQueryParam = cmccDaProductService.getProductListByQueryParam(cmccDaProductListReq);
        return getDataTable(productListByQueryParam);
    }

    /**
     * 聚合商品列表查询
     */
    @PreAuthorize("@ss.hasPermi('system:product:merge:list')")
    @PostMapping("/mergeCardList")
    public TableDataInfo mergeCardList(@RequestBody CmccDaProductListReq cmccDaProductListReq) {
        startPage();
        //确保是聚合商品
        cmccDaProductListReq.setMergeProductFlag("1");
        List<CmccDaProduct> productListByQueryParam = cmccDaProductService.getProductListByQueryParam(cmccDaProductListReq);
        return getDataTable(productListByQueryParam);
    }

    /**
     * 分流商品列表查询
     *
     * @param cmccDaProductListReq 选择分流商品查询参数封装
     * @return 选择分流商品列表
     */
    @PreAuthorize("@ss.hasPermi('system:product:flow:list')")
    @PostMapping("/selectFlowProductList")
    public TableDataInfo selectFlowProductList(@RequestBody CmccDaProductListReq cmccDaProductListReq) {
        startPage();
        List<CmccDaProduct> productListByQueryParam = cmccDaProductService.getProductListByQueryParam(cmccDaProductListReq);
        return getDataTable(productListByQueryParam);
    }

    @PostMapping("/checkBanArea")
    AjaxResult checkBanArea(@RequestBody CheckBanAreaReq checkBanAreaReq) {
        CmccDaProduct one = cmccDaProductService.getOne(new LambdaUpdateWrapper<CmccDaProduct>()
                .eq(CmccDaProduct::getProductCode, checkBanAreaReq.getProductCode()), false);
        if (one == null){
            return error("当前产品不存在或存在商品编码相同的产品");
        }
        ReqResult reqResult = cmccDaProductService.checkBanArea(checkBanAreaReq.getProvinceCode(), one);
        return reqResult.getCode() == 200 ? success() : error(reqResult.getMsg());
    }

    /**
     * 推荐商品添加
     */
    @PreAuthorize("@ss.hasPermi('system:product:add')")
    @PostMapping("/add")
    AjaxResult add(@RequestBody CmccDaProductAddReq cmccDaProductAddReq) {
        //System.out.println("添加" + cmccDaProductAddReq);
        cmccDaProductService.addProduct(cmccDaProductAddReq);
        return success();
    }

    /**
     * 聚合商品添加
     *
     * @param cmccDaProductAddReq 聚合商品实例
     * @return 请求状态
     */
    @PreAuthorize("@ss.hasPermi('system:product:flow:add')")
    @PostMapping("/addMergeCard")
    AjaxResult addMergeCard(@RequestBody CmccDaProductAddReq cmccDaProductAddReq) {
        cmccDaProductService.addMergeProduct(cmccDaProductAddReq);
        return success();
    }

    /**
     * 推荐商品删除
     *
     * @param cmccDaCardDelReq 参数封装
     * @return 请求状态
     */
    @PreAuthorize("@ss.hasPermi('system:product:remove')")
    @PostMapping("/del")
    AjaxResult del(@RequestBody @Valid CmccDaCardDelReq cmccDaCardDelReq) {
        //按照id 删除推荐商品信息
        cmccDaProductService.removeProductById(cmccDaCardDelReq.getId());
        return success();
    }

    /**
     * 推荐商品更新
     */
    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @PostMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult update(@RequestBody CmccDaProductUpdateReq cmccDaProductUpdateReq) {
        //System.out.println("修改" + cmccDaProductUpdateReq);
        cmccDaProductService.updateProductById(cmccDaProductUpdateReq);
        return success();
    }

    /**
     * 获取推荐商品列表信息
     *  推荐商品列表
     */
    @PostMapping("/recommendedList")
    public AjaxResult getRecommendedList(@RequestBody CmccDaProductListReq cmccDaProductListReq) {
//        System.out.println("cmccDaProductListReq = " + cmccDaProductListReq);
        // 设置推广渠道
        SysUser sysUser = sysUserMapper.selectUserById(getUserId());
//        System.out.println("sysUser = " + sysUser.getDeptId());
        if (sysUser.getDeptId() == 101) cmccDaProductListReq.setPromoteChannel("0");
        if (sysUser.getDeptId() == 102) cmccDaProductListReq.setPromoteChannel("1");
//        System.out.println("cmccDaProductListReq = " + cmccDaProductListReq);
        List<Recommended> recommendedList = cmccDaProductService.getRecommendedList(cmccDaProductListReq);
        return AjaxResult.success(recommendedList);
    }

    /**
     * 获取推荐总链接的商品列表信息
     */
    @PostMapping("/promotionAllRecommendList")
    public AjaxResult promotionAllRecommendList(@RequestBody CmccDaProductListReq cmccDaProductListReq) {
        // 设置推广渠道
        SysUser sysUser = sysUserMapper.selectUserById(cmccDaProductListReq.getUserId());
        if (sysUser.getDeptId() == 101) cmccDaProductListReq.setPromoteChannel("0");
        if (sysUser.getDeptId() == 102) cmccDaProductListReq.setPromoteChannel("1");
        List<Recommended> recommendedList = cmccDaProductService.getRecommendedList(cmccDaProductListReq);
        List<Recommended> collect = recommendedList.stream().filter(f -> "1".equals(f.getPromotionFlag())).collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

    /**
     * 收藏商品列表
     */
    @PostMapping("/collectProductList")
    public AjaxResult collectProductList(@RequestBody CmccDaProductListReq cmccDaProductListReq) {
        cmccDaProductListReq.setCollectFlag("1");
        List<Recommended> recommendedList = cmccDaProductService.getCollectProductList(cmccDaProductListReq);
        return AjaxResult.success(recommendedList);
    }

    /**
     * 商品名称列表
     */
    @PostMapping("/getProductNameList")
    public AjaxResult getProductNameList(@RequestBody CmccDaProductListReq cmccDaProductListReq) {
        List<Recommended> recommendedList = cmccDaProductService.getCollectProductList(cmccDaProductListReq);
        List<String> productNameList = recommendedList.stream().map(Recommended::getProductName).collect(Collectors.toList());
        return AjaxResult.success(productNameList);
    }



    @PostMapping("/getPlaceOrderImg")
    AjaxResult getMainImagUrl(@RequestBody String productCode) {
        return AjaxResult.success(cmccDaProductService.getPlaceOrderImgByProductCode(productCode));
    }


    /**
     * 根据商品ID 获取商品信息
     * @param productCode 商品id
     * @return 商品信息
     */
    @PostMapping("/getCardById")
    AjaxResult getCardById(@RequestBody String productCode) {
//        System.out.println("IpUtils.getIpAddr() = " + IpUtils.getIpAddr());
        System.out.println("IpUtils.getIpAddressByVectorIndex = " + IpUtils.getIpAddressByOnline("27.209.144.70"));
        return success(cmccDaProductService.getByProductCode(productCode));
    }

    /**
     * 获取链接失效状态
     */
    @PostMapping("/linkFailureStatus")
    AjaxResult getLinkFailureStatus(@RequestBody String productCode){
        return success(cmccDaProductService.getLinkFailureStatus(productCode));
    }

    /**
     * 获取链接失效状态
     */
    @PostMapping("/getLimitActiveTime")
    AjaxResult getLimitActiveTime(@RequestBody String productCode){
        return success(cmccDaProductService.getLimitActiveTime(productCode));
    }

    /**
     * 获取链接失效状态
     */
    @PostMapping("/getLimitAreas")
    AjaxResult getLimitAreas(@RequestBody String productCode){
        return success(cmccDaProductService.getLimitAreas(productCode));
    }

    /**
     * 上线产品
     */
    @PreAuthorize("@ss.hasPermi('system:product:online')")
    @PostMapping("/onlineProductByCode")
    AjaxResult onlineProductByCode(@RequestBody String productCode){
        ReqResult reqResult = cmccDaProductService.onlineProductByCode(productCode);
        return reqResult.getCode() == 200 ? success() : error(reqResult.getMsg());
    }

    /**
     * 下架产品
     */
    @PreAuthorize("@ss.hasPermi('system:product:offline')")
    @PostMapping("/offlineProductByCode")
    AjaxResult offlineProductByCode(@RequestBody String productCode){
        ReqResult reqResult = cmccDaProductService.offlineProductByCode(productCode);
        return reqResult.getCode() == 200 ? success() : error(reqResult.getMsg());
    }

    /**
     * 设置当日限单
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    @PreAuthorize("@ss.hasPermi('system:order:limit:set')")
    @PostMapping("/setTodayOrderLimit")
    public AjaxResult setTodayOrderLimit(@RequestBody @Valid TodayOrderLimitDto todayOrderLimitDto){
        // 设置本产品当日限单量
        cmccDaProductService.lambdaUpdate()
                .eq(CmccDaProduct::getProductCode, todayOrderLimitDto.getProductCode())
                .set(CmccDaProduct::getProductTodayOrderLimit, todayOrderLimitDto.getProductLimit())
                .set(CmccDaProduct::getAgentTodayOrderLimit, todayOrderLimitDto.getAgentLimit())
                .update();
        // 设置所有代理当前商品的当日限单量
        cmccDaProxyProductManageService.lambdaUpdate()
                .eq(CmccDaProxyProductManage::getProductCode, todayOrderLimitDto.getProductCode())
                .set(CmccDaProxyProductManage::getTodayOrderLimit, todayOrderLimitDto.getAgentLimit())
                .update();
        return success();
    }
}
